package com.hangzhou.xyj.engine.download;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.model.AppVersionModel;
import com.hangzhou.xyj.utils.ToastUtil;

import java.io.File;

/**
 * Created by dfb on 2015/4/10.
 */
public class DownloadUtil {
    private static final String TAG = "DownloadUtil";
    // 下载通知ID
    private static final int DOWNLOAD_NOTIFY_ID = 1;
    private static boolean isDownloading = false;
    private static NotificationManager manager;
    private static NotificationCompat.Builder notificationBuilder;

    public static void downloadApk(final Context context, AppVersionModel model) {
        if (isDownloading) {
            ToastUtil.show("应用正在下载...");
            return;
        }

        //1.prepare savepath
        String dir = isFolderExist("download");
        final String apkPath = dir + "//" + model.apkName;

        //2.starting download
        FinalHttp fh = new FinalHttp();
        String apkUrl = model.ForcedUpdate ? model.ComUpUrl.trim() : model.url.trim();

        // 参数：第一个apk地址，第二个保存apk地址，第三个是否断点续传
        fh.download(apkUrl, apkPath, true, new FileAjaxCallBack(context, apkPath));

    }


    private static String isFolderExist(String dir) {
        File folder = Environment.getExternalStoragePublicDirectory(dir);
        if (!(folder.exists() && folder.isDirectory())) {
            folder.mkdirs();
        }
        return folder.getAbsolutePath();
    }

    /**
     * 安装apk
     *
     * @param context
     * @param filePath
     */
    private static void installApk(Context context, String filePath) {
        Uri uri = Uri.fromFile(new File(filePath));
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setDataAndType(uri, "application/vnd.android.package-archive");
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(install);
    }

    /**
     * 下载进度通知
     *
     * @param context
     * @param progress
     */
    public static void notifyDownload(Context context, int progress) {
        if (context == null || progress < 0)
            return;
        if(notificationBuilder ==null) {
            manager = (NotificationManager)
                    context.getSystemService(Context.NOTIFICATION_SERVICE);
            String title = context.getString(R.string.app_name);
            String contentText = "正在下载";
            notificationBuilder = new NotificationCompat.Builder(context);
            notificationBuilder.setSmallIcon(R.drawable.icon);
            notificationBuilder.setContentTitle(title);
            notificationBuilder.setContentText(contentText);
        }
       // notificationBuilder.setNumber(progress);
        notificationBuilder.setProgress(100, progress, false);
        if(progress ==100) {
            notificationBuilder.setProgress(0, 0, false);
            notificationBuilder.setContentText("下载完毕！");
        }

        manager.notify(DOWNLOAD_NOTIFY_ID, notificationBuilder.build());
    }

    /**
     * 取消下载通知
     *
     * @param context
     */
    public static void cancelDownload(Context context) {
        NotificationManager manager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancel(DOWNLOAD_NOTIFY_ID);
    }

    private static class FileAjaxCallBack extends AjaxCallBack<File> {
        private final Context mContext;
        private final String mApkPath;

        public FileAjaxCallBack(Context context, String apkPath) {
            mContext = context;
            mApkPath = apkPath;
        }

        @Override
        public void onStart() {
            super.onStart();
            ToastUtil.show("开始下载...");
        }

        @Override
        public void onFailure(Throwable t, int errorCode, String strMsg) {
            super.onFailure(t, errorCode, strMsg);
            //标记下载false
            isDownloading = false;
            if (!TextUtils.isEmpty(errorCode + "")
                    && errorCode == 416) {  //416表示download complete
                ToastUtil.show("应用已下载，无需重新下载...");
                installApk(mContext, mApkPath);
            } else {
                ToastUtil.show("下载失败，请重试...");
            }
            cancelDownload(mContext);
        }


        @Override
        public void onLoading(long count, long current) {
            super.onLoading(count, current);
            //标记为正在下载
            isDownloading = true;
            int progress = (int) (current * 100 / count);
            notifyDownload(mContext, progress);
        }

        @Override
        public void onSuccess(File file) {
            super.onSuccess(file);
            //标记下载false
            isDownloading = false;
            ToastUtil.show("下载完成");
            installApk(mContext, file.getAbsolutePath());
            cancelDownload(mContext);
        }
    }
}
